package com.example.roam.game.qcmountain.bird.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;

import com.example.roam.game.qcmountain.bird.control.GameControl;

public class GameUI extends SurfaceView implements SurfaceHolder.Callback {
    private GameControl gameControl;
    private SurfaceHolder surfaceHolder;

    public GameUI(Context context) {
        super(context);
        init();
    }
    public GameUI(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public GameUI(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    public GameUI(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }
    public void init(){
        gameControl = new GameControl(getContext());
        surfaceHolder = this.getHolder();
        surfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        Runner runner = new Runner();
        runner.start();
    }
    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }
    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    class Runner extends Thread{
        @Override
        public void run() {
            while (!gameControl.isOver()) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                if (gameControl.isLife) {
                    Canvas canvas = surfaceHolder.lockCanvas();
                    drawAll(canvas);
                    surfaceHolder.unlockCanvasAndPost(canvas);
//                }
            }
        }
    }

    public void drawAll(Canvas canvas){
        gameControl.draw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gameControl.onTouch(event);
        return super.onTouchEvent(event);
    }

    public GameControl getGameControl() {
        return gameControl;
    }
}
